# coding: utf-8
import cv2
import os
import time
from matplotlib import pyplot as plt
import numpy as np

chess = cv2.imread('character.png')
chess_h, chess_w, _ = chess.shape
MI6_W = 1080
index = 0

print(chess_h, chess_w)

def screen_shot():
    os.system('adb shell screencap -p /sdcard/autojump.png')
    os.system('adb pull /sdcard/autojump.png .')

def find_chess(im):
    _, score, _, pos = cv2.minMaxLoc(cv2.matchTemplate(im, chess, cv2.TM_CCOEFF_NORMED))
    return score, pos

def jump(distance):
    press_time = max(int(distance * 1.18), 200)
    os.system('adb shell input swipe 643 1560 643 1560 {0}'.format(press_time))

def get_distance(chess_x, chess_y, im):
    global index

    if chess_x + chess_w / 2 < MI6_W / 2:
        # 棋子在左边的情况
        w = MI6_W - (chess_x + chess_w)
        h = w * 5 / 7
        y0, y1 = chess_y + chess_h / 2 - h, chess_y + chess_h / 2
        x0, x1 = chess_x + chess_w + 10, MI6_W - 1
    else:
        # 棋子在右边的情况
        w = chess_x
        h = w * 5 / 7
        y0, y1 = chess_y + chess_h / 2 - h, chess_y + chess_h / 2 
        x0, x1 = 0, w - 10

    area = im[round(y0):round(y1), round(x0):round(x1)]
    canny = cv2.Canny(area, 1, 10)

    target_x = int(x0 + np.where(canny == 255)[1][0] + 0.5) + 10

    cv2.line(im, (round(target_x), round(y0)), (round(target_x), round(y1)), (0, 0, 0), 3)
    cv2.imwrite('./debug/{0}.png'.format(index), im)
    index += 1
    
    distance = abs(chess_x + chess_w / 2 - target_x)

    return int(distance * 1.414)

def game():
    global index

    while True:
        screen_shot()

        im = cv2.imread('autojump.png')
        score, (x, y) = find_chess(im)

        cv2.rectangle(im, (x, y), (x + chess_w, y + chess_h), (255, 0, 0), 3)
        if score < 0.5:
            index = 0
            break

        distance = get_distance(x, y, im)

        # plt.imshow(im)
        # plt.show()
        # break

        jump(distance)

        time.sleep(1.5)

if __name__ == '__main__':
    game()
